import { Component, ViewChild, ElementRef } from '@angular/core';
import { IonicPage, NavController, ViewController, NavParams } from 'ionic-angular';
import { HttpProvider } from '../../providers/http/http';
import { StorageProvider } from '../../providers/storage/storage';
import { DialogProvider } from '../../providers/dialog/dialog';
import { DomSanitizer } from "@angular/platform-browser";
import { FileUploader } from 'ng2-file-upload';
import { UserInfoProvider } from '../../providers/user-info/user-info';
import { user_info } from '../login/login';
import { LoadingController, Loading } from 'ionic-angular';
import { Camera, CameraOptions } from '@ionic-native/camera';
import { ImagePicker,ImagePickerOptions } from '@ionic-native/image-picker';
import { ActionSheetController } from 'ionic-angular';

declare var $:any;
declare var cropper:any;
/**
 * Generated class for the ImgEditPage page.
 *
 * See https://ionicframework.com/docs/components/#navigation for more info on
 * Ionic pages and navigation.
 */
@IonicPage()
@Component({
  selector: 'page-img-edit',
  templateUrl: 'img-edit.html',
})
export class ImgEditPage {

  oldname: any;
  member_id: any;

  // h.set('Content-Type','application/json;charset=utf-8');
  public selectedImgUrl: any[] = [];//存储已经选择的图片
  selectedImgLength = 0;



  // 图片base64
  public base64Img: any;
  public base64name: any;
  //用户信息
  userInfo: user_info = new user_info();


  constructor(
    public navCtrl: NavController,
    public viewCtrl: ViewController,
    public navParams: NavParams,
    public http: HttpProvider,
    public storage: StorageProvider,
    public dialog: DialogProvider,
    private sanitizer: DomSanitizer,
    public user: UserInfoProvider,
    private camera: Camera,
    private imagePicker: ImagePicker,
    public actionSheetCtrl: ActionSheetController,
  	public loadingCtrl: LoadingController) { }

  ionViewDidLoad() {
    console.log('ionViewDidLoad NicknameEditPage');
    this.userInfo = this.user.getuserInfo();
    this.member_id = this.userInfo.member_id;
//	console.log("1:"+this.selectedImgUrl[0]);

	let _this2 = this;
	$(function(){
  console.log("2:"+_this2.selectedImgUrl[0]);
  var $image = $('#image');
  var options = {
//	autoCrop: false,
	dragMode:'move',
    aspectRatio: 1 / 1,
    width:'200',
    height:'200',
    crop: function (e) {
    }
  };
	
  $image.cropper(options);
  
  $("#ok").click(function(){
	  	if ($image.data('cropper')) {
	  		var result = $image.cropper('getCroppedCanvas', options);
	  		
			if (result) {
				var quality = 0.1; 
				var base64Codes=result.toDataURL("image/jpeg", quality);
				_this2.selectedImgUrl[0] = base64Codes;
    			_this2.base64Img = base64Codes;
    			_this2.base64name = 'userNow.jpg';
    			console.log("3:"+_this2.selectedImgUrl[0]);
				console.log("4:"+_this2.base64Img);
    			console.log("5:"+_this2.base64name);
		  	}
	  	}
	})
  
	// Import image
//var $inputImage = $('.filePrew');
////var URL = window.URL || window.webkitURL;
//var blobURL;

 /* if (URL) {
    $inputImage.change(function () {
      var files = this.files;
      var file;

      if (!$image.data('cropper')) {
        return;
      }

      if (files && files.length) {
        file = files[0];

        if (/^image\/\w+$/.test(file.type)) {
          blobURL = URL.createObjectURL(file);//新图片的路径
          $image.one('built.cropper', function () {

            // Revoke when load complete
            URL.revokeObjectURL(blobURL);
          }).cropper('reset').cropper('replace', blobURL);
          $inputImage.val('');
          $("button").show();
          _this2.base64name = file.name;
          console.log("6:"+ _this2.base64name);
        } else {
          window.alert('Please choose an image file.');
        }
      }
    });
  } */
  
  
	})
  }
  
  
  presentActionSheet() {
    const actionSheet = this.actionSheetCtrl.create({
      title: '请选择',
      buttons: [
        {
          text: '拍照',
          role: 'destructive',
          handler: () => {
            console.log('拍照 clicked');
            this.takePhoto();
          }
        },{
          text: '相册',
          handler: () => {
            console.log('相册 clicked');
            this.selectPhoto();
          }
        },{
          text: '取消',
          role: 'cancel',
          handler: () => {
            console.log('取消 clicked');
          }
        }
      ]
    });
    actionSheet.present();
  }
  
   takePhoto(){
   	const options: CameraOptions = {
	  quality: 50,
	  destinationType: this.camera.DestinationType.DATA_URL,
	  encodingType: this.camera.EncodingType.JPEG,
	  mediaType: this.camera.MediaType.PICTURE,
//	  allowEdit:true,
//	  sourceType:this.camera.PictureSourceType.CAMERA,
	};
	this.camera.getPicture(options).then((imageData) => {
		 // imageData is either a base64 encoded string or a file URI
		 // If it's base64 (DATA_URL):
		 let base64Image = 'data:image/jpeg;base64,' + imageData;
		 
//		 this.selectedImgUrl[0] = base64Image;
//		 this.base64Img = base64Image;
//		 this.base64name = 'userNow.jpg';
		 
		 var $image = $('#image');
         $image.one('built.cropper', function () {
         }).cropper('reset').cropper('replace', base64Image);
         $("#ok").show();
	}, (err) => {
	 // Handle error
	});
   }
   selectPhoto(){
   	const options: CameraOptions = {
	  quality: 50,
	  destinationType: this.camera.DestinationType.DATA_URL,
	  encodingType: this.camera.EncodingType.JPEG,
	  mediaType: this.camera.MediaType.PICTURE,
	  sourceType:this.camera.PictureSourceType.PHOTOLIBRARY,
//	  allowEdit:true,
	};
	this.camera.getPicture(options).then((imageData) => {
		 // imageData is either a base64 encoded string or a file URI
		 // If it's base64 (DATA_URL):
		 let base64Image = 'data:image/jpeg;base64,' + imageData;
		 
//		 this.selectedImgUrl[0] = base64Image;
//		 this.base64Img = base64Image;
//		 this.base64name = 'userNow.jpg';
		 
		 var $image = $('#image');
         $image.one('built.cropper', function () {
         }).cropper('reset').cropper('replace', base64Image);
         $("#ok").show();
	}, (err) => {
	 // Handle error
	});
   	
    }

//photoCompress(file, w, objDiv) {
//  let _this = this;
//  var ready = new FileReader();
//  /*开始读取指定的Blob对象或File对象中的内容. 当读取操作完成时,readyState属性的值会成为DONE,如果设置了onloadend事件处理程序,则调用之.同时,result属性中将包含一个data: URL格式的字符串以表示所读取文件的内容.*/
//  ready.readAsDataURL(file);
//  ready.onload = function () {
//    var re = this.result;
//
//    _this.canvasDataURL(re, w, objDiv)
//  }
//}
//canvasDataURL(path, obj, callback) {
//  var img = new Image();
//  img.src = path;
//  img.onload = function () {
//    var that = img;
//    // 默认按比例压缩
//    var w = that.width,
//      h = that.height,
//      scale = w / h;
//    //              w = obj.width || w;
//    //              h = obj.height || (w / scale);
//    w = 300;
//    h = 300;
//    var quality = 0.1;  // 默认图片质量为0.7
//    //生成canvas
//    var canvas = document.createElement('canvas');
//    var ctx = canvas.getContext('2d');
//    // 创建属性节点
//    //              var anw = document.createAttribute("width");
//    //              anw.nodeValue = w;
//    //              var anh = document.createAttribute("height");
//    //              anh.nodeValue = h;
//    //              canvas.setAttributeNode(anw);
//    //              canvas.setAttributeNode(anh);
//    //替代
//    canvas.width = w;
//    canvas.height = h;
//    ctx.drawImage(that, 0, 0, w, h);
//    // 图像质量
//    if (obj.quality && obj.quality <= 1 && obj.quality > 0) {
//      quality = obj.quality;
//    }
//    // quality值越小，所绘制出的图像越模糊
//    var base64 = canvas.toDataURL('image/jpeg', quality);
//    // 回调函数返回base64的值
//    callback(base64);
//  }
//}

//upLoadImag(event) {
//  if (!event) {
//    return;
//  }
//  var fileImg = event.target.files[0];
//  //		if (fileImg) {
//  //           if ((fileImg.size/ 1024) > 1024) {
//  //           	console.log("文件大于1M");
//  //           	this.dialog.showAlert("图片大小不能超过1M","");
//  //    			return;
//  //           }
//  //      }
//  let promise = new Promise((success) => {
//    let _this2 = this;
//    _this2.photoCompress(fileImg, {
//      quality: 0.2
//    }, function (base64Codes) {
//      //                    console.log("压缩后：" + base.length / 1024 + " " + base);
//      // console.log("dd:__" + base64Codes);
//      _this2.selectedImgUrl[0] = base64Codes;
//      _this2.base64Img = base64Codes
//    });
//
//
//    //			var reader = new FileReader();
//    //			this.selectedImgUrl[0] = this.sanitizer.bypassSecurityTrustUrl(window.URL.createObjectURL(fileImg));
//    //			reader.readAsDataURL(fileImg);
//    //			reader.onload = function(e) {
//    //				success(this);
//    //			}
//  });
//
//  //回调
//  promise.then(data => {
//    //			//就是base64
//    //    this.base64Img = data['result'];
//
//  })
//  // //上传成功
//  // event.target.value = "";
//  this.base64name = fileImg.name;
//}

  saveImg() {
    if (!this.base64Img) {
      this.dialog.showAlert("没有选择图片", "");
      return;
    }
	let loading = this.loadingCtrl.create({
	    content: '保存中...'
	});
	loading.present();
    this.http.postJson('', 'member/member/headportrait',
      {
        "product_id": this.member_id,//会员附件ID
        "file_type_id": "1",//附件类型 1.会员头像，2.营业执照扫描件，3.合同扫描件，4.营业执照扫描件，5.安装场地，6.申诉信息图片,7广告文件，8软文展示图，9电表记录表    
        "tables": "1",//所属表1会员表2主体表3物业表4广告表5软文表6电表记录表7申诉表   
        "base64_img_list": [{
          "img": this.base64Img,
          "name": this.base64name
        },
        ]
      }, '').then(res => {
      	loading.dismiss();
        if (res['status'] == 200) {
          this.dialog.showAlert(res['message'], '');
          this.navCtrl.setRoot("CenterPage")
        }
      });

  }
}
